<script setup lang="ts">
import { ref, computed } from 'vue';
import { message } from 'ant-design-vue';
import { CloudUploadOutlined, SendOutlined, MobileOutlined, LaptopOutlined } from '@ant-design/icons-vue';
import type { FileTransfer, DeviceInfo } from '../types';

const transfers = ref<FileTransfer[]>([]);
const selectedDevices = ref<DeviceInfo[]>([]);
const isUploading = ref(false);
const uploadProgress = ref(0);
const transferType = ref<'cloud' | 'direct'>('direct');
const password = ref('');

const mockDevices: DeviceInfo[] = [
  {
    id: '1',
    name: 'iPhone 13',
    type: 'mobile',
    connectionType: 'lan',
    status: 'connected',
    platform: 'ios'
  },
  {
    id: '2',
    name: 'MacBook Pro',
    type: 'desktop',
    connectionType: 'lan',
    status: 'connected',
    platform: 'macos'
  }
];

const connectedDevices = computed(() => mockDevices.filter(d => d.status === 'connected'));

const handleFileSelect = async (file: File) => {
  if (!file) return;
  
  isUploading.value = true;
  uploadProgress.value = 0;

  // 模拟上传进度
  const interval = setInterval(() => {
    if (uploadProgress.value < 100) {
      uploadProgress.value += 10;
    } else {
      clearInterval(interval);
      isUploading.value = false;
      
      // 添加到传输列表
      transfers.value.unshift({
        id: crypto.randomUUID(),
        fileName: file.name,
        fileSize: file.size,
        progress: 100,
        status: 'completed',
        type: 'send',
        transferType: transferType.value,
        password: transferType.value === 'cloud' ? password.value : undefined,
        targetDevices: transferType.value === 'direct' ? selectedDevices.value : undefined
      });

      message.success('文件上传成功！');

      // 重置表单
      password.value = '';
      selectedDevices.value = [];
      uploadProgress.value = 0;
    }
  }, 300);
};

const beforeUpload = (file: File) => {
  handleFileSelect(file);
  return false;
};

const formatFileSize = (size: number) => {
  if (size < 1024) return `${size} B`;
  if (size < 1024 * 1024) return `${(size / 1024).toFixed(2)} KB`;
  if (size < 1024 * 1024 * 1024) return `${(size / 1024 / 1024).toFixed(2)} MB`;
  return `${(size / 1024 / 1024 / 1024).toFixed(2)} GB`;
};
</script>

<template>
  <div class="file-transfer">
    <a-card :bordered="false" class="transfer-card">
      <a-radio-group v-model:value="transferType" button-style="solid" class="transfer-options">
        <a-radio-button value="direct">
          <template #icon><send-outlined /></template>
          直接传输
        </a-radio-button>
        <a-radio-button value="cloud">
          <template #icon><cloud-upload-outlined /></template>
          云端传输
        </a-radio-button>
      </a-radio-group>

      <a-upload-dragger
        :showUploadList="false"
        :beforeUpload="beforeUpload"
        class="upload-area"
      >
        <p class="ant-upload-drag-icon">
          <component :is="transferType === 'direct' ? SendOutlined : CloudUploadOutlined" />
        </p>
        <p class="ant-upload-text">
          点击或拖拽文件至此处
          {{ transferType === 'direct' ? '发送至选中设备' : '上传至云端' }}
        </p>
      </a-upload-dragger>

      <template v-if="transferType === 'cloud'">
        <div class="upload-options">
          <a-input-password
            v-model:value="password"
            placeholder="设置密码保护（可选）"
            class="password-input"
          />
        </div>
      </template>

      <template v-else>
        <div class="device-selection">
          <a-typography-title :level="5">选择目标设备：</a-typography-title>
          <a-row :gutter="[16, 16]" class="device-grid">
            <a-col :span="12" v-for="device in connectedDevices" :key="device.id">
              <a-card
                :bordered="false"
                :class="['device-card', { selected: selectedDevices.includes(device) }]"
                @click="selectedDevices.includes(device) 
                  ? selectedDevices = selectedDevices.filter(d => d.id !== device.id)
                  : selectedDevices.push(device)"
              >
                <template #avatar>
                  <component :is="device.type === 'mobile' ? MobileOutlined : LaptopOutlined" />
                </template>
                <a-card-meta
                  :title="device.name"
                  :description="device.platform"
                />
                <template #extra>
                  <a-checkbox :checked="selectedDevices.includes(device)" />
                </template>
              </a-card>
            </a-col>
          </a-row>
        </div>
      </template>

      <a-progress
        v-if="isUploading"
        :percent="uploadProgress"
        :status="uploadProgress === 100 ? 'success' : 'active'"
        class="upload-progress"
      />
    </a-card>

    <a-card :bordered="false" class="transfers-list">
      <template #title>传输历史</template>
      <a-list
        :dataSource="transfers"
        class="transfers-grid"
      >
        <template #renderItem="{ item }">
          <a-list-item>
            <a-card :bordered="false" :class="['transfer-item', item.status]">
              <a-row align="middle" :gutter="16">
                <a-col :span="16">
                  <a-typography-text strong>{{ item.fileName }}</a-typography-text>
                  <br />
                  <a-space>
                    <a-typography-text type="secondary">{{ formatFileSize(item.fileSize) }}</a-typography-text>
                    <a-tag :color="item.transferType === 'cloud' ? 'blue' : 'green'">
                      {{ item.transferType === 'cloud' ? '云端传输' : '直接传输' }}
                    </a-tag>
                  </a-space>
                </a-col>
                <a-col :span="8">
                  <a-progress
                    :percent="item.progress"
                    :status="item.status === 'completed' ? 'success' : 
                            item.status === 'failed' ? 'exception' : 'active'"
                    size="small"
                  />
                </a-col>
              </a-row>
            </a-card>
          </a-list-item>
        </template>
      </a-list>
    </a-card>
  </div>
</template>

<style scoped>
.file-transfer {
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.transfer-card {
  background: var(--bg-light);
}

.transfer-options {
  margin-bottom: 2rem;
  width: 100%;
  display: flex;
  justify-content: center;
}

.upload-area {
  margin: 2rem 0;
  background: var(--bg-dark);
}

.upload-options {
  margin-top: 1rem;
}

.password-input {
  max-width: 300px;
  margin: 0 auto;
  display: block;
}

.device-selection {
  margin-top: 2rem;
}

.device-card {
  background: var(--bg-dark);
  transition: all 0.3s ease;
}

.device-card.selected {
  border-color: var(--primary-color);
  background: rgba(24, 144, 255, 0.1);
}

.transfers-list {
  background: var(--bg-light);
}

.transfer-item {
  background: var(--bg-dark);
  margin-bottom: 1rem;
}

.transfer-item.completed :deep(.ant-progress-bg) {
  background-color: #52c41a;
}

.transfer-item.failed :deep(.ant-progress-bg) {
  background-color: #ff4d4f;
}

/* 覆盖一些 Ant Design Vue 的默认样式 */
:deep(.ant-card-head) {
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

:deep(.ant-upload-drag) {
  background: var(--bg-dark);
  border: 2px dashed rgba(255, 255, 255, 0.1);
}

:deep(.ant-upload-drag:hover) {
  border-color: var(--primary-color);
}

:deep(.ant-progress-text) {
  color: var(--text-primary);
}

:deep(.ant-card-meta-title) {
  color: var(--text-primary);
}

:deep(.ant-card-meta-description) {
  color: var(--text-secondary);
}
</style> 